# python
from flask import Blueprint, request, jsonify, current_app
from flask_restful import marshal

from ..common.Result import response, response_failure
from ..models.food import Food, food_fields
from .. import db

food_bp = Blueprint('food_bp', __name__)

from werkzeug.utils import secure_filename
import os
from flask import send_from_directory
import hashlib
UPLOAD_FOLDER = os.path.join(os.path.dirname(__file__), '..', 'photo', 'food')
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
current_app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER



@food_bp.route('/photo/food/<filename>')
def uploaded_file(filename):
    return send_from_directory(current_app.config['UPLOAD_FOLDER'], filename)


@food_bp.route('/food/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return response_failure(msg="没有文件部分")
    file = request.files['file']
    if file.filename == '':
        return response_failure(msg="没有选择文件")
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        md5_filename = hashlib.md5(filename.encode()).hexdigest() + os.path.splitext(filename)[1]
        file.save(os.path.join(UPLOAD_FOLDER, md5_filename))
        return response(data={'filename': 'http://127.0.0.1:5000/photo/food/'+md5_filename}, msg="文件上传成功")
    return response_failure(msg="不允许的文件类型")

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@food_bp.route('/food', methods=['POST'])
def create_food():
    data = request.get_json()
    data['create_time'] = db.func.now()
    food = Food(**data)
    db.session.add(food)
    db.session.commit()
    return response(data=food.to_dict(), msg="食物创建成功！")

@food_bp.route('/food/<int:id>', methods=['GET'])
def get_food(id):
    food = Food.query.get(id)
    if food is None:
        return response_failure(msg="没有这个食物")
    return response(data=food.to_dict())



@food_bp.route('/food/query', methods=['POST'])
def query_food():
    data = request.get_json()

    # 默认分页参数
    page = data.get('page', 1)  # 当前页，默认为第1页
    per_page = data.get('per_page', 10)  # 每页记录数，默认为10条

    query = Food.query

    # 处理普通的等值查询
    for key, value in data.items():
        if hasattr(Food, key) and not isinstance(value, dict) and not key.endswith('_start') and not key.endswith(
                '_end'):
            query = query.filter(getattr(Food, key) == value)

    # 处理范围查询 (field_start, field_end)
    float_fields = [
        'food_calorie', 'food_protein', 'food_fat', 'food_carbohydrate',
        'food_fiber', 'food_vitamin_a', 'food_vitamin_b', 'food_vitamin_c',
        'food_vitamin_e', 'food_carotene', 'food_cholesterol', 'food_mg',
        'food_ca', 'food_fe', 'food_zn', 'food_se', 'food_cu', 'food_mn',
        'food_k', 'food_p', 'food_na'
    ]

    # 处理以 _start 和 _end 结尾的字段
    for field in float_fields:
        start_key = f"{field}_start"
        end_key = f"{field}_end"

        # 检查是否有 _start 和 _end 的查询条件
        start_value = data.get(start_key, None)
        end_value = data.get(end_key, None)

        if start_value is not None and end_value is not None:
            query = query.filter(getattr(Food, field).between(start_value, end_value))
        elif start_value is not None:
            query = query.filter(getattr(Food, field) >= start_value)
        elif end_value is not None:
            query = query.filter(getattr(Food, field) <= end_value)

    # 执行分页查询
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)

    # 获取当前页的记录
    food_list = [food.to_dict() for food in pagination.items]

    # 返回分页信息和当前页的数据
    return jsonify({
        'total': pagination.total,  # 总记录数
        'pages': pagination.pages,  # 总页数
        'current_page': pagination.page,  # 当前页
        'per_page': pagination.per_page,  # 每页条目数
        'has_next': pagination.has_next,  # 是否有下一页
        'has_prev': pagination.has_prev,  # 是否有上一页
        'foods': food_list  # 当前页的食物数据
    })

@food_bp.route('/food/<int:id>', methods=['PUT'])
def update_food(id):
    data = request.get_json()
    food = Food.query.get_or_404(id)
    # 更新食物属性
    for key, value in data.items():
        if hasattr(food, key):
            setattr(food, key, value)

    db.session.commit()
    return response(msg='食物信息更新成功！')

@food_bp.route('/food/<int:id>', methods=['DELETE'])
def delete_food(id):
    food = Food.query.get_or_404(id)
    db.session.delete(food)
    db.session.commit()
    return response(msg='食物信息删除成功！')
# python

@food_bp.route('/food/batch_delete', methods=['DELETE'])
def batch_delete_food():
    data = request.get_json()
    ids = data.get('ids', [])

    if not ids:
        return response_failure(msg="没有提供要删除的食物ID列表")

    # 批量删除食物
    Food.query.filter(Food.id.in_(ids)).delete(synchronize_session=False)
    db.session.commit()

    return response(msg='批量删除食物成功！')

